package br.mg.bhe.ftpobre.fs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPListParseEngine;
import org.apache.commons.net.ftp.FTPSClient;

import br.mg.bhe.ftpobre.CustomUnixFTPEntryParser;
import br.mg.bhe.ftpobre.Main;
import br.mg.bhe.ftpobre.log.FtpLogView;
import br.mg.bhe.ftpobre.util.LogUtil;

/**
 * 
 * @author Aureliano
 */
public class RemoteFileLocalizer implements IFileLocalizer<RemoteFile> {

	private static final Logger logger = LogUtil.getLogger(RemoteFileLocalizer.class);
	
	@Override
	public List<RemoteFile> loadFiles(String path) {
		return this.loadFtpFiles(path);
	}
	
	private List<RemoteFile> loadFtpFiles(String folder) {
		try {
			FTPSClient c = (FTPSClient) Main.getConnectionData().getFtpClient();
			String message = "Alterando diretório de trabalho para '" + ((folder.equals("")) ? "raiz" : folder) + "'";
			logger.info(message);
			FtpLogView.log(message);
			FTPListParseEngine e = c.initiateListParsing(CustomUnixFTPEntryParser.class.getName(), folder);
			List<RemoteFile> files = new ArrayList<RemoteFile>();
			
			while (e.hasNext()) {
				for (FTPFile f : e.getNext(70000)) {
					if (f != null) {
						RemoteFile rm = new RemoteFile();
						rm.setFile(f);
						files.add(rm);
					}
				}
			}
			
			return files;
		} catch (IOException ex) {
			throw new RuntimeException(ex);
		}
	}
}